package com.shop.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.shop.config.DateJsonValueProcessor;
import com.shop.dao.UserInfoMapper;
import com.shop.pojo.GoodsCollection;
import com.shop.pojo.User;
import com.shop.pojo.UserAddress;
import com.shop.pojo.UserInfo;
import com.shop.result.JsonResult;
import com.shop.service.LoginService;
import com.shop.service.UserInfoService;
import com.shop.util.BaseUtil;
import net.sf.json.JsonConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private LoginService loginService;
    @Autowired
    private MongoTemplate mongoTemplate;

    /*定义集合名称*/
    private static final String collectionName = "userInfo";

    /*个人信息查询*/
    @Override
    public JsonResult queryUserInfoByCondition(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String data = request.getParameter("data");
        String token =  request.getParameter("token");
        User user = loginService.getUserByToken(token);     //验证用户信息是否已过期
        if(null == user){
            return new JsonResult(false,"查询失败！该用户token已失效或不存在，请重试");
        }

        Map<String,Object> params = null;
        if(StringUtils.isNotEmpty(data)){
            params = BaseUtil.json2Map(data);
        }else{
            params = new HashMap<>();
        }

        params.put("userId",user.getUserId());
        List<UserInfo> userInfos = new ArrayList<>();

        /*Mysql操作*/
//        userInfos = userInfoMapper.queryUserInfoByCondition(params);

        /*MongoDB操作*/
        Query query = new Query();
        query.fields().exclude("_id");
//        query.fields().include(collectionName);   //指定只返回的key对应value值

        for (Map.Entry<String,Object> map : params.entrySet()) {
            query.addCriteria(Criteria.where(map.getKey()).is(map.getValue()));
        }

        userInfos = mongoTemplate.find(query, UserInfo.class,collectionName);
        return new JsonResult(true,userInfos,null,userInfos.size());
    }

    /*个人信息添加*/
    @Override
    public JsonResult addUserInfoByToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String data = request.getParameter("data");
        String token =  request.getParameter("token");
        User user = loginService.getUserByToken(token);     //验证用户信息是否已过期
        if(null == user){
            return new JsonResult(false,"添加失败：用户已失效，请重新登录后再试");
        }

        Map<String,Object>params = new HashMap<>();
        params.put("userId",user.getUserId());

        /*Mysql操作*/
//        List<UserInfo> userInfos = userInfoMapper.queryUserInfoByCondition(params);
//        if(userInfos.size() > 0){
//            return new JsonResult(false,"添加失败：用户信息已存在，请勿重复添加");
//        }

        /*MongoDB操作*/
//        Query isExistQuery = new Query();
//        isExistQuery.addCriteria(Criteria.where("userId").is(user.getUserId()));
//        isExistQuery.fields().include(collectionName); //只显示用户信息
//        isExistQuery.fields().exclude("_id");  //不显示MongoDB数据库中生成的id值
//        Map<String,Object> isInfo = mongoTemplate.findOne(isExistQuery, Map.class, collectionName);
//        if(isInfo != null){
//            return new JsonResult(false,"添加失败：用户信息已存在，请勿重复添加");
//        }

        data = BaseUtil.dataTranscoding(data);
        String dataJson = BaseUtil.toJson(data);    //把数据转化为Json字符串
        UserInfo userInfo = JSONObject.parseObject(dataJson,UserInfo.class);
        userInfo.setInfoId(BaseUtil.getSID());
        userInfo.setUserId(user.getUserId());
        userInfo.setUserName(user.getUserName());
        userInfo.setCreateTime(new Date());

        /*Mysql操作*/
//        userInfoMapper.insert(userInfo);

        /*MongoDB操作*/
        mongoTemplate.insert(userInfo,collectionName);

        return new JsonResult(true,"添加用户信息成功！");
    }

    /*个人信息修改*/
    @Override
    public JsonResult updateUserInfoByToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String data = request.getParameter("data");
        String token =  request.getParameter("token");
        User user = loginService.getUserByToken(token);     //验证用户信息是否已过期
        if(null == user){
            return new JsonResult(false,"更新失败：用户已失效，请重新登录后再试");
        }

        data = BaseUtil.dataTranscoding(data);
        String dataJson = BaseUtil.toJson(data);    //把数据转化为Json字符串
        UserInfo userInfo = JSONObject.parseObject(dataJson,UserInfo.class);
//        userInfo.setUpdateTime(new Date());

        /*Mysql操作*/
//        userInfoMapper.updateByPrimaryKey(userInfo);

        /*MongoDB操作*/
        Query query = new Query();
        query.addCriteria(Criteria.where("userId").is(user.getUserId()));
        Update update = new Update();

        Map<String,Object> dataParams = BaseUtil.json2Map(data);
        for (Map.Entry<String,Object> map : dataParams.entrySet()) {
            update.set(map.getKey(),map.getValue());
        }

        update.set("updateTime",new Date());
        mongoTemplate.updateMulti(query,update,collectionName);

        return new JsonResult(true,"修改用户信息成功！");
    }

    /*个人信息删除*/
    @Override
    public JsonResult deleteUserInfoByToken(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String infoId = request.getParameter("infoId");
        if(StringUtils.isNotEmpty(infoId)){
            /*Mysql操作*/
//            userInfoMapper.deleteByPrimaryKey(infoId);

            /*MongoDB操作*/
            Query query = new Query();
            query.addCriteria(Criteria.where("infoId").is(infoId));

            UserInfo userInfo = mongoTemplate.findOne(query,UserInfo.class);  //查询MongoDB数据中的单条数据
            if (userInfo != null){    //当查询出来的数据不为空时，方可执行remove方法
                mongoTemplate.remove(query, GoodsCollection.class,collectionName);
            }

            return new JsonResult(true,"删除用户信息成功！");
        }

        return new JsonResult(true,"删除用户信息失败！该用户信息不存在，请重新检查");
    }

}
